<?php
namespace Admin\Model;

use Think\Model;

class GoodsModel extends Model
{
    //添加时调用create方法允许接收的字段
    protected $insertFields = array('goods_name','market_price','shop_price','is_on_sale','goods_desc','brand_id');
    //添加时调用create方法允许接收的字段
    protected $updateFields = array('id','goods_name','market_price','shop_price','is_on_sale','good_desc','brand_id');
    //定义验证规则
    protected $_validate  = array(
        array('cat_id','require','必须选择主分类',1),
        array('goods_name','require','商品名称不能为空!',1),
        array('market_price','currency','市场价格必须是货币类型!',1),
        array('shop_price','currency','本店价格必须是货币类型!',1),
    );

    public function getDate(){
        return date('Y-m-d H:i:s',time());
    }

    protected function _before_insert(&$data,$option)
    {
        $data['addtime'] = date('Y-m-d H:i:s',time());
        $data['goods_desc'] = removeXSS($_POST['goods_desc']);

        //判断有没有选择图片
        if($_FILES['logo']['error'] == 0)
        {
            $upload = new \Think\Upload();
            $upload->maxSize = 1024*1024; //1M
            $upload->exts = array('jpg','gif','png','jpeg');
            $upload->rootPath = './Public/Uploads/';
            $upload->savepath = 'Goods/';
            $info = $upload->upload();
            if(!$info){
                $this->error = $upload->getError();
                return FALSE;
            }
            else
            {
                $logo = $info['logo']['savepath'].$info['logo']['savename'];
                $mbiglogo = $info['logo']['savepath'].'mbig_'.$info['logo']['savename'];
                $biglogo = $info['logo']['savepath'].'big_'.$info['logo']['savename'];
                $midlogo = $info['logo']['savepath'].'mid_'.$info['logo']['savename'];
                $smlogo = $info['logo']['savepath'].'sm_'.$info['logo']['savename'];
                $image = new \Think\Image();
                $image->open('./Public/Uploads/'.$logo);
                $image->thumb(700,700)->save('./Pbulic/Uploads/'.$mbiglogo);
                $image->thumb(350,350)->save('./Pbulic/Uploads/'.$biglogo);
                $image->thumb(130,130)->save('./Pbulic/Uploads/'.$midlogo);
                $image->thumb(50,50)->save('./Pbulic/Uploads/'.$smlogo);
                $data['logo'] = $logo;
                $data['mbig_logo'] = $mbiglogo;
                $data['big_logo'] = $biglogo;
                $data['mid_logo'] = $midlogo;
                $data['sm_logo'] = $smlogo;
            }
        }
        if($_FILES['logo']['error'] == 0)
        {
            $ret = uploadOne('logo','Goods',array(
               array(700,700),
               array(350,350),
               array(130,130),
               array(50,50),
            ));
            $data['logo'] = $ret['images'][0];
            $data['mbig_logo'] = $ret['images'][1];
            $data['big_logo'] = $ret['images'][2];
            $data['mid_logo'] = $ret['images'][3];
            $data['sm_logo'] = $ret['images'][4];
        }
    }
    public function search($perPage = 3){
        $where = array();
        $gn = I('get.gn');
        if($gn)
            $where['goods_name'] = array('like',"%$gn%");
        $fp = I('get.fp');
        $tp = I('get.tp');
        if($fp && $tp)
            $where ['shop_price'] = array('between',array($fp,$tp));
        elseif ($fp)
            $where['market_price'] = array('egt',$fp);
        elseif ($tp)
            $where['shop_price'] = array('elt',$tp);
        $ios = I('get.ios');
        if($ios)
            $where['is_on_sale'] = array('eq',$ios);
        $fa = I('get.fa');
        $ta = I('get.ta');
        if($fa && $ta)
            $where['addtime'] = array('between',array($fa,$ta));
        elseif ($fa)
            $where['addtime'] = array('egt',$fa);
        elseif ($ta)
            $where['addtime'] = array('elt',$ta);

        $brandId = I('get.brand_id');
        if($brandId)
            $where['a.brand_id'] = array('eq',$brandId);

        $count = $this->where($where)->count();
        $pageObj = new \Think\Page($count,$perPage);
        $pageObj->setConfig('next','下一页');
        $pageObj->setConfig('prev','上一页');
        $pageString = $pageObj->show();
        $orderby = 'id';
        $orderway = 'desc';
        $odby = I('get.odby');
        if($odby)
        {
            if($odby == 'id_asc')
                $orderway = 'asc';
            elseif($odby == 'price_desc')
                $orderby = 'shop_price';
            elseif($odby == 'price_asc')
            {
                $orderby = 'shop_price';
                $orderway = 'asc';
            }
        }
        $data = $this->order("$orderby $orderway")
//        ->field('a.*,b.brand_name')
//        ->alias('a')
//        ->join('LEFT JOIN __BRAND__ b ON a.brand_id=b.id')
        ->where($where)
        ->limit($pageObj->firstRow.','.$pageObj->listRows)
        ->select();
//        var_dump($data);
//        die;
        return array(
            'data' => $data,
            'page' => $pageString,
        );
    }

    protected function _before_update(&$data,$option)
    {
        $id = $option['where']['id']; //要修改的id
        $ecid = I('post.ext_cat_id');
        $gcModel = D('goods_cat');
        //先删除原分类数据
        $gcModel->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();
        if($ecid)
        {
            foreach ($ecid as $k => $v)
            {
                if(empty($v))
                    continue;
                $gcModel->add(array(
                    'cat_id' => $v,
                    'goods_id' => $id
                ));
            }
        }
        if(isset($_FILES['pic']))
        {
            $pics = array();
            foreach ($_FILES['pic']['name'] as $k => $v)
            {
                $pics[] = array(
                    'name' => $v,
                    'type' => $_FILES['pic']['type'][$k],
                    'tmp_name' => $_FILES['pic']['tmp_name'][$k],
                    'error' => $_FILES['pic']['error'][$k],
                    'size' => $_FILES['pic']['size'][$k],
                );
            }
            $_FILES = $pics;
            $gpModel = D('goods_pic');
            foreach ($pics as $k => $v)
            {
                if($v['error'] == 0)
                {
                    $ret = uploadOne($k,'Goods',array(
                        array(650,650),
                        array(350,350),
                        array(50,50),
                    ));
                    if($ret['ok'] == 1)
                    {
                        $gpModel->add(array(
                            'pic' => $ret['images'][0],
                            'big_pic' => $ret['images'][1],
                            'mid_pic' => $ret['images'][2],
                            'sm_pic' => $ret['images'][3],
                            'goods_id' => $id,
                        ));
                    }
                }
            }
        }
        //处理会员价格
        $mp = I('post.member_price');
        $mpModel = D('member_price');
        $mpModel->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();
        foreach ($mp as $k => $v)
        {
            $_v = (float)$v;
            if($_v > 0)
            {
                $mpModel->add(array(
                    'price' =>$_v,
                    'level_id' => $k,
                    'goods_id' => $id,
                ));
            }
        }

        //判断有没有选择图片
        if($_FILES['logo']['error'] == 0)
        {
            $upload = new \Think\Upload();
            $upload->maxSize = 1024*1024; //1M
            $upload->exts = array('jpg','gif','png','jpeg');
            $upload->rootPath = './Public/Uploads/';
            $upload->savepath = 'Goods/';
            $info = $upload->upload();
            if(!$info){
                $this->error = $upload->getError();
                return FALSE;
            }
            else
            {
                $logo = $info['logo']['savepath'].$info['logo']['savename'];
                $mbiglogo = $info['logo']['savepath'].'mbig_'.$info['logo']['savename'];
                $biglogo = $info['logo']['savepath'].'big_'.$info['logo']['savename'];
                $midlogo = $info['logo']['savepath'].'mid_'.$info['logo']['savename'];
                $smlogo = $info['logo']['savepath'].'sm_'.$info['logo']['savename'];
                $image = new \Think\Image();
                $image->open('./Public/Uploads/'.$logo);
                $image->thumb(700,700)->save('./Pbulic/Uploads/'.$mbiglogo);
                $image->thumb(350,350)->save('./Pbulic/Uploads/'.$biglogo);
                $image->thumb(130,130)->save('./Pbulic/Uploads/'.$midlogo);
                $image->thumb(50,50)->save('./Pbulic/Uploads/'.$smlogo);
                $data['logo'] = $logo;
                $data['mbig_logo'] = $mbiglogo;
                $data['big_logo'] = $biglogo;
                $data['mid_logo'] = $midlogo;
                $data['sm_logo'] = $smlogo;

                //先查出原来图片的路径
                $oldLogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);
                //从硬盘上删除
                unlink('./Public/Uploads/'.$oldLogo['logo']);
                unlink('./Public/Uploads/'.$oldLogo['mbig_logo']);
                unlink('./Public/Uploads/'.$oldLogo['big_logo']);
                unlink('./Public/Uploads/'.$oldLogo['mid_logo']);
                unlink('./Public/Uploads/'.$oldLogo['sm_logo']);
            }
        }
        $data['goods_desc'] = removeXSS($_POST['goods_desc']);
    }

    protected function _before_delete(&$data,$option)
    {
        $id = $option['where']['id'];
        $gpModel = D('goods_pic');
        $pics = $gpModel->field('pic,sm_pic,mid_pic,big_pic')->where(array(
            'goods_id' => array('eq',$id),
        ))->select();
        foreach ($pics as $k => $v)
            delectImage($v);
        $gpModel->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();
        $oldLogo = $this->field('logo,mbig_logo,big_logo,mid_logo,sm_logo')->find($id);
        deleteImage($oldLogo);
        //删除会员价格
        $mpModel = D('member_price');
        $mpModel->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();

        //删除扩展分类
        $gcModel = D('goods_cat');
        $gcModel->where(array(
            'goods_id' => array('eq',$id),
        ))->delete();
    }

    protected function _after_insert($data,$option){
        $mp = I('post.member_price');
        $mpModel = D('member_price');
        foreach ($mp as $k => $v)
        {
            $_v = (float)$v;
            if($_v > 0)
            {
                $mpModel->add(array(
                   'price' => $_v,
                    'level_id' => $k,
                    'goods_id' => $data['id'],
                ));
            }
        }

        $ecid = I('post.ext_cat_id');
        if($ecid)
        {
            $gcModel = D('goods_cat');
            foreach ($ecid as $k => $v)
            {
                if(empty($v))
                    continue;
                $gcModel->add(array(
                     'cat_id' => $v,
                    'goods_id' => $data['id'],
                ));
            }
        }

        if(isset($_FILES['pic']))
        {
            $pics = array();
            foreach ($_FILES['pic']['name'] as $k => $v)
            {
                $pics[] = array(
                    'name' => $v,
                    'type' => $_FILES['pic']['type'][$k],
                    'tmp_name' => $_FILES['pic']['tmp_name'][$k],
                    'error' => $_FILES['pic']['error'][$k],
                    'size' => $_FILES['pic']['size'][$k],
                );
            }
            $_FILES = $pics;
            $gpModel = D('goods_pic');
            foreach ($pics as $k => $v)
            {
                if($v['error'] == 0)
                {
                    $ret = uploadOne($k,'Goods',array(
                        array(650,650),
                        array(350,350),
                        array(50,50),
                    ));
                    if($ret['ok'] == 1)
                    {
                        $gpModel->add(array(
                            'pic' => $ret['images'][0],
                            'big_pic' => $ret['images'][1],
                            'mid_pic' => $ret['images'][2],
                            'sm_pic' => $ret['images'][3],
                            'goods_id' => $data['id'],
                        ));
                    }
                }
            }
        }
    }
}
